storing unbound python functions in a class object

I'm trying to do the following in python:

In a file called foo.py:

# simple function that does something:
def myFunction(a,b,c):
  print "call to myFunction:",a,b,c

# class used to store some data:
class data:
  fn = None

# assign function to the class for storage.
data.fn = myFunction

And then in a file called bar.py: import foo

d = foo.data
d.fn(1,2,3)

However, I get the following error:

TypeError: unbound method f() must be called with data instance as first argument (got int instance instead)

This is fair enough I suppose - python is treating d.myFunction as a class method. However, I want it to treat it as a normal function - so I can call it without having to add an unused 'self' parameter to the myFunction definition.

So the question is:

How can I store a function in a class object without the function becoming bound to that class?


Asked by: Maria721 | Posted: 01-10-2021






Answer 1

data.fn = staticmethod(myFunction)

should do the trick.

Answered by: Chester145 | Posted: 02-11-2021



Answer 2

What you can do is:

d = foo.data()
d.fn = myFunction

d.fn(1,2,3)

Which may not be exactly what you want, but does work.

Answered by: Cherry309 | Posted: 02-11-2021



Answer 3

Thanks to Andre for the answer - so simple!

For those of you who care, perhaps I should have included the entire context of the problem. Here it is anyway:

In my application, users are able to write plugins in python. They must define a function with a well-defined parameter list, but I didn't want to impose any naming conventions on them.

So, as long as users write a function with the correct number of parameters and types, all they have to do is something like this (remember, this is the plugin code):

# this is my custom code - all plugins are called with a modified sys.path, so this
# imports some magic python code that defines the functions used below.
from specialPluginHelperModule import *

# define the function that does all the work in this plugin:
def mySpecialFn(paramA, paramB, paramC):
    # do some work here with the parameters above:
    pass

# set the above function:
setPluginFunction(mySpecialFn)

The call to setPluginFunction takes the function object and sets it in a hidden class object (along with other plugin-configuration related stuff, this example has been simplified somewhat). When the main application wants to run the function, I use the runpy module to run the plugin code, and then extract the class object mentioned above - this gives me the configuration data and the plugin function so I can run it cleanly (without polluting my namespace).

This entire process is repeated multiple times for different plugins over the same input, and seems to work very well for me.

Answered by: Roman446 | Posted: 02-11-2021



Similar questions

Storing functions in a sparse array with Python

I have a relatively large enum wherein each member represents a message type. A client will receive a message containing the integer value associated with the msg type in the enum. For each msg type there will be an individual function callback to handle the msg. I'd like to make the lookup and dispatching of the callback as quick as possible by using a sparse array (or vector) in which the enum value maps to the ...


python - Storing functions without calling them

I have a module which has a function that will generate a sequence 'n' items long. I then have specific sequence names that will generate a specific set of items associated with that name. My issue is that I don't want the module to actually build all the sequences during definition, but only build it once that name is called. My current scheme is like so (the actual gen_sequence function is much more complica...


python - Trying to import all functions from a file and storing them in a list

For context, I am trying to solve questions from a website, and for each question I am usually implementing 2-3 solutions via a function for each solution. I time each function using a timing wrapper, and I call each questions' solution python file from a global main.py. Now, what I am currently doing in the main.py is from problem1 import func1, func2, func3 l = [func1, func2, func3] for x in l: x(argum...


variadic functions - Passing on named variable arguments in python

Say I have the following methods: def methodA(arg, **kwargs): pass def methodB(arg, *args, **kwargs): pass In methodA I wish to call methodB, passing on the kwargs. However, it seems that if I define methodA as follows, the second argument will be passed on as positional rather than named variable arguments. def methodA(arg, **kwargs): methodB("arg...


python - Running unit tests on nested functions

I come from the Java world, where you can hide variables and functions and then run unit tests against them using reflection. I have used nested functions to hide implementation details of my classes so that only the public API is visible. I am trying to write unit tests against these nested functions to make sure that I don't break them as I develop. I have tried calling one of the nested functions like:


python - Porting MATLAB functions to Scilab. How do I use symbolic?

I'm porting some MATLAB functions to Scilab. The cool thing is that there is a conversion toolbox that make things very easy. The problem is I did not find the counterpart to...


python - Parsing Functions

I'm making a script parser in python and I'm a little stuck. I am not quite sure how to parse a line for all its functions (or even just one function at a time) and then search for a function with that name, and if it exists, execute that function short of writing a massive list if elif else block.... EDIT This is for my own scripting language that i'm making. its nothing very complex, but i have a...


python - How to call java objects and functions from CPython?

I have a python program, which runs on the CPython implementation, and inside it I must call a function defined in a java program. How can I do this? It would be nice to be able to use some java objects too. Jython is not an option. I must run the python part in CPython.


Passing functions which have multiple return values as arguments in Python

So, Python functions can return multiple values. It struck me that it would be convenient (though a bit less readable) if the following were possible. a = [[1,2],[3,4]] def cord(): return 1, 1 def printa(y,x): print a[y][x] printa(cord()) ...but it's not. I'm aware that you can do the same thing by dumping both return values into temporary variables, but it doesn't seem as elega...


Passing self to class functions in Python

This question already has answers here:


c# - Import python functions into a .NET language?

I am a C# .NET programmer and am learning Python. I have downloaded IronPython, and know that it can call into .NET libraries. I'm wondering whether there is a way to do the reverse, that is to call into some existing "classic" Python libraries in my C# code, maybe using .NET Interop. I'd like to be able to access functions in libraries such as pygame.


Python Hash Functions

What is a good way of hashing a hierarchy (similar to a file structure) in python? I could convert the whole hierarchy into a dotted string and then hash that, but is there a better (or more efficient) way of doing this without going back and forth all the time? An example of a structure I might want to hash is: a -> b1 -> c -> 1 -> d a -> b2 -> c -> 2 -> d a -> c ...


Passing functions with arguments to another function in Python?

This question already has answers here:






Still can't find your answer? Check out these communities...



PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python



top