I have module foo, inside this module I dynamically created class:
def superClassCreator():
return type("Bar", (object,), {})
Now, what I want to achieve is to make this new dynamic class visible as a class of this module:
import foo
dir(foo)
>>> [... 'Bar' ...]
Do you know how to do this?
Python Code can be dynamically imported and classes can be dynamically created at run-time. Classes can be dynamically created using the type() function in Python. The type() function is used to return the type of the object. The above syntax returns the type of object.
To load dynamically a module call import(path) as a function with an argument indicating the specifier (aka path) to a module. const module = await import(path) returns a promise that resolves to an object containing the components of the imported module. } = await import(path);
In the __init__.py file of a package __all__ is a list of strings with the names of public modules or other objects. Those features are available to wildcard imports. As with modules, __all__ customizes the * when wildcard-importing from the package.
You can use Bar = superClassCreator()
in foo
(at the module level).
Alternatively, from another module, you can add Bar
as an attribute on foo
:
import foo
foo.Bar = superClassCreator()
or, if the name must be taken from the generated class:
import foo
generatedClass = superClassCreator()
setattr(foo, generatedClass.__name__, generatedClass)
From within the foo
module, you can set it directly on globals()
:
generatedClass = superClassCreator()
globals()[generatedClass.__name__] = generatedClass
del generatedClass
with an optional del
statement to remove the generatedClass
name from the namespace again.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With