mirror of
https://github.com/micropython/micropython.git
synced 2026-01-06 12:10:13 +01:00
py/runtime: Support importing a method from an instance.
This change follows CPython behaviour, allowing use of:
from instance import method
to import a bound method from a class instance, eg registered via
setting `sys.modules["instance"] = instance`.
Admittedly this is probably a very rarely used pattern in Python, but it
resolves a long standing comment about whether or not this is actually
possible (it turns out it is possible!). A test is added to show how it
works.
The main reason for this change is to fix a problem with imports in the
webassembly port: prior to this fix, it was not possible to do `from
js_module import function`, where `js_module` is a JavaScript object
registered to be visible to Python through the webassembly API function
`registerJsModule(js_module)`. But now with this fix that is possible.
Signed-off-by: Damien George <damien@micropython.org>
This commit is contained in:
38
tests/basics/import_instance_method.py
Normal file
38
tests/basics/import_instance_method.py
Normal file
@@ -0,0 +1,38 @@
|
||||
# Test importing a method from a class instance.
|
||||
# This is not a common thing to do, but ensures MicroPython has the same semantics as CPython.
|
||||
|
||||
import sys
|
||||
|
||||
if not hasattr(sys, "modules"):
|
||||
print("SKIP")
|
||||
raise SystemExit
|
||||
|
||||
|
||||
class A:
|
||||
def __init__(self, value):
|
||||
self.value = value
|
||||
|
||||
def meth(self):
|
||||
return self.value
|
||||
|
||||
def meth_with_arg(self, a):
|
||||
return [self.value, a]
|
||||
|
||||
|
||||
# Register a class instance as the module "mod".
|
||||
sys.modules["mod"] = A(1)
|
||||
|
||||
# Try importing it as a module.
|
||||
import mod
|
||||
|
||||
print(mod.meth())
|
||||
print(mod.meth_with_arg(2))
|
||||
|
||||
# Change the module.
|
||||
sys.modules["mod"] = A(3)
|
||||
|
||||
# Try importing it using "from ... import".
|
||||
from mod import meth, meth_with_arg
|
||||
|
||||
print(meth())
|
||||
print(meth_with_arg(4))
|
||||
Reference in New Issue
Block a user