Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 875
Thomi Avatar asked Nov 29 '08 12:11

Thomi


2 Answers

data.fn = staticmethod(myFunction)

should do the trick.

like image 55
André Avatar answered Oct 23 '22 18:10

André


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.

like image 38
Matthew Schinckel Avatar answered Oct 23 '22 18:10

Matthew Schinckel