How do I add a function dynamically to a MicroPython object?
In standard python "MethodType" is used for this, but it seems missing from MicroPython. Is there a workaround?
Thanks,
Bernhard
Dynamically add method to instance
Dynamically add method to instance
Bernhard Boser
Dynamically add method to instance
Obj.thing = function
?
Sent from my iPhone using Tapatalk Pro
?
Sent from my iPhone using Tapatalk Pro
Re: Dynamically add method to instance
I don't think that binds it to the instance. Hence no reference to "self".
I used a global as a workaround. Not pretty, but works.
I used a global as a workaround. Not pretty, but works.
Bernhard Boser
Re: Dynamically add method to instance
Have you actually tried it?ttmetro wrote:I don't think that binds it to the instance. Hence no reference to "self".
I used a global as a workaround. Not pretty, but works.
Sent from my iPhone using Tapatalk Pro
Re: Dynamically add method to instance
yes!
Also what I found with a web search is that this is exactly what is for.
Also what I found with a web search is that this is exactly what
Code: Select all
MethodType
Bernhard Boser
Re: Dynamically add method to instance
Not 100% sure what you mean, can you give an example maybe?
Possibly you mean something like
?
Possibly you mean something like
Code: Select all
class Foo:
pass
def Stuff(obj):
print('Stuff', obj)
f = Foo()
print(f)
f.stuff = lambda: Stuff(f)
f.stuff()
Re: Dynamically add method to instance
I believe Bernhard is talking about adding a member function to an instance of a class. MethodType is the standard way to do this. It appears to be implemented in the micropython-lib types module.
Re: Dynamically add method to instance
Yes, that's what I want:
Result:
So seems like a feature that is missing from MicroPython. Fortunately there is a workaround, at least for my case.
Thanks for all the suggestions!
Code: Select all
from types import MethodType
class DynamicTest:
def __init__(self):
self.x = 5
def a(self):
return self.x
dt = DynamicTest()
def b(self):
return self.x
dt.b = b
def c(self):
return self.x
setattr(dt, 'c', MethodType(c, dt))
print('a', dt.a())
# print('b', dt.b())
print('c', dt.c())
- a works as expected.
- b fails: TypeError: function takes 1 positional arguments but 0 were given (also expected)
- c fails: TypeError: cannot create 'bound_method' instances
So seems like a feature that is missing from MicroPython. Fortunately there is a workaround, at least for my case.
Thanks for all the suggestions!
Bernhard Boser