Created
March 29, 2017 19:10
-
-
Save arthuralvim/1bdb8f67caf81d87fcf5c1b57f6c3bbb to your computer and use it in GitHub Desktop.
Creating modules with Python.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| def import_code(code, name, add_to_sys_modules=0): | |
| """ | |
| Import dynamically generated code as a module. code is the | |
| object containing the code (a string, a file handle or an | |
| actual compiled code object, same types as accepted by an | |
| exec statement). The name is the name to give to the module, | |
| and the final argument says wheter to add it to sys.modules | |
| or not. If it is added, a subsequent import statement using | |
| name will return this module. If it is not added to sys.modules | |
| import will try to load it in the normal fashion. | |
| import foo | |
| is equivalent to | |
| foofile = open("/path/to/foo.py") | |
| foo = importCode(foofile,"foo",1) | |
| Returns a newly generated module. | |
| """ | |
| module = imp.new_module(name) | |
| exec(code, module.__dict__) | |
| if add_to_sys_modules: | |
| sys.modules[name] = module | |
| return module | |
| if __name__ == '__main__': | |
| module_base = 'tests.transform.meta.x' | |
| code = \ | |
| """ | |
| def function_1(obj, *args, **kwargs): | |
| return 1 | |
| """ | |
| module_imported = import_code(code, module_base) | |
| module_imported.function_1() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment