2

In python I can do:

exec(code_string, globals(), some_object.__dict__)

to add a method to an object. Is it possible to add a static method to a class in some sort of similar fashion? Like:

exec(code_string, globals(), ClassName.__dict__)

So that I could then statically call the method:

ClassName.some_static_method()

What I'm trying to do is add new staticmethods during runtime given some python code defining the method. i.e. if I was given:

code_string = '''
@staticmethod
def test():
    return 'blah'
'''

how can I create and instantiate this into a class so that I could call it?

Hopefully I was clear enough, thank you!

EDIT: working example of adding a function to an object:

class TestObject(object):
    pass

code_string = '''
def test():
return 'blah'
'''
t = TestObject()
exec(code_string, globals(), t.__dict__)
lanthica
  • 250
  • 1
  • 9
  • The first expression, following "In python I can do:" gives a `TypeError: 'dictproxy' object does not support item assignment` in any case – samstav Sep 04 '13 at 17:23
  • I can't get the formatting in this comment so I added it to the post. – lanthica Sep 04 '13 at 17:35

1 Answers1

2

Use setattr()

>>> code_string = '''
... @staticmethod
... def test():
...     return 'returning blah'
... '''
>>>
>>> exec(code_string)

>>> test
<staticmethod object at 0x10fd25c58>

>>> class ClassName(object):
...     def instancemethod(self):
...             print "instancemethod!"
...
>>> setattr(ClassName, 'teststaticmethod', test)

>>> ClassName.teststaticmethod()
'returning blah'
>>>

And here's an article on being safe with exec() and eval() in python.

samstav
  • 1,945
  • 1
  • 20
  • 20
  • Thanks, I think I'll use this tactic, though the only problem with it is that it requires me to provide the name for the function. I can think of a few ways to work with this though, thanks again! – lanthica Sep 04 '13 at 17:55
  • 1
    I was wondering if that would be an issue for you. I'll give it some more thought! – samstav Sep 04 '13 at 17:57