Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python how to register dynamic class in module

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?

like image 609
mnowotka Avatar asked Nov 29 '12 11:11

mnowotka


People also ask

How do you create a dynamic class in Python?

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.

How do you dynamically import a module using a function?

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);

What is __ all __ in Python?

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.


1 Answers

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.

like image 108
Martijn Pieters Avatar answered Oct 04 '22 00:10

Martijn Pieters