How would one go about importing only a specific class from a Python module using its path?
I need to import a specific class from a Python file using the file path. I have no control over the file and its completely outside of my package.
file.py:
class Wanted(metaclass=MyMeta):
...
class Unwanted(metaclass=MyMeta):
...
The metaclass implementation is not relevant here. However, I will point out that it's part of my package and I have full control over it.
Import example:
spec = importlib.util.spec_from_file_location(name='Wanted', location="path_to_module/mudule.py")
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
This works, and Wanted
is imported. The problem is that Unwanted
is also imported. In fact, as long as there is any string value given for name
(including an empty string), both Wanted
and Unwanted
are imported from the module.
This has the same effect as in the example before, where both Wanted
and Unwanted
are imported:
importlib.util.spec_from_file_location(name='random string', location="path_to_module/mudule.py")
I'm not looking for a specific solution using importlib
; any reasonable way will do. I will point out that I don't have a need of using the class when it's imported, I only need the import to happen and my metaclass will take care of the rest.
CodePudding user response:
If I am not mistaken, the name parameter is just used to name the module you are importing. But, more importantly, when you are importing any module, you are executing the whole file, which means that in your case both of these classes will be created. It would not matter whether you wrote from file import Wanted
, import file
or used any other form of the import statement. To prevent creation of a class object at the import time, you would need to put the entire class block inside a function, which only at the time of its invocation would create a class object and then, for example, return the reference to it.
A Python program is constructed from code blocks. A block is a piece of Python program text that is executed as a unit. The following are blocks: a module, a function body, and a class definition.
Source: https://docs.python.org/3/reference/executionmodel.html#structure-of-a-program
CodePudding user response:
since you named your file "file.py":
from file import Wanted
If your file is in a folder, you can use:
from folder.file import Wanted