This question may sound similar to the following, but I'm not sure how to apply their solutions to my use-case:
How to import a module given the full path?
Can you use a string to instantiate a class?
I have a class Foo
defined and imported in my project. However, at runtime I may have a string containing a different definition of Foo
(along with lots of other classes and import
statements). I'd like to be able to replace the already loaded Foo
with the one in my string, in a way that after the operation, anybody who instantiates f = Foo()
would instantiate the definition from my string. At the same time, I'd like to ignore any other definitions/imports in my string. How to do this?
Assume the following project structure and use-case:
project/
__init__.py
mytypes/
__init__.py
foo.py # contains the definition 'class Foo'
another_package/
bar.py
main.py
Inside main.py
and bar.py
I have from mytypes.foo import Foo
. After the replace operation detailed above I want both to use the new definition of Foo
from the replacement string, but no other definition from my string.
Aucun commentaire:
Enregistrer un commentaire