简体   繁体   中英

Impoting specific Class from a Python module with `importlib`

How would one go about importing 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 relavant here,
however, I will point out that its part of my package and I have full contol 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.
Infact, as long as there ANY srt value given for name (including empty string)
both Wanted & Unwanted are imported from the module.

This has the same effect as in the example before, where both Wanted & 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
and any reasonable way will do.
I will point out that I dont have a need of using the Class when its imported,
I only need the import to happen and my Metaclass will take care of the rest.

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

First of all, if I am not mistaken, the 'name' parameter is just a name you're giving to the module you are trying to import. And secondly, when you are importing any module, you are basically executing every single line of code in it, so in this case both of these classes are created. It doesn't matter if you use "from module import foo" or just "import module". The only difference is that in the first case, "foo" will become available from the global namespace.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM