python-importlib

How to modify imported source code on-the-fly?

How to modify imported source code on-the-fly? Question: Suppose I have a module file like this: # my_module.py print(“hello”) Then I have a simple script: # my_script.py import my_module This will print “hello”. Let’s say I want to “override” the print() function so it returns “world” instead. How could I do this programmatically (without manually …

Total answers: 6

Import class from module dynamically

Import class from module dynamically Question: I have class called ‘my_class’ placed in ‘my_module’. And I need to import this class. I tried to do it like this: import importlib result = importlib.import_module(‘my_module.my_class’) but it says: ImportError: No module named ‘my_module.my_class’; ‘my_module’ is not a package So. As I can see it works only for …

Total answers: 2

Python importlib's analogue for imp.new_module()

Python importlib's analogue for imp.new_module() Question: PyCharm shows me that imp is deprecated so I wonder if there any analogue of imp.new_module for importlib. Asked By: user2558053 || Source Answers: Quoting from documentation (Emphasis mine) – imp.new_module(name) Return a new empty module object called name. This object is not inserted in sys.modules. Deprecated since version …

Total answers: 2

How to import a module in Python with importlib.import_module

How to import a module in Python with importlib.import_module Question: I’m trying to use importlib.import_module in Python 2.7.2 and run into the strange error. Consider the following dir structure: a | + – __init__.py – b | + – __init__.py – c.py a/b/__init__.py has the following code: import importlib mod = importlib.import_module(“c”) (In real code …

Total answers: 3