Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
167 views
in Technique[技术] by (71.8m points)

Is there a way to dynamically import Python objects?

I'm trying to make a command handler, here's some code:

from importlib import import_module
from os import path, listdir

client.commands = [] # where the commands are stored
directory = '.\src\exec\files'
for command in listdir(directory):
    filepath = path.join(directory, filename)
    if path.isdir(filepath) and 'lib' not in filepath: # check if file is a directory
        log_commands(directory=filepath) # make recursive logging

    elif filename.endswith('.py'):
        command_name = filename.split('\')[-1]
        module_name = devutils.filepath2module(filepath, True, True) # convert file path to module path
        client_utils.commands[command_name] = import_module(module_name) # puts module in a new item

The code works fine, but the import_module function imports only the entire function. I was wondering if there's some library that imports specific objects from the module, like:

from module import object

But in a dynamic way, I searched a little bit and couldn't find anything. (Sorry for bad english)

question from:https://stackoverflow.com/questions/65839170/is-there-a-way-to-dynamically-import-python-objects

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

from module import foo is equivalent to foo = __import__('module').foo. It does have to run the whole file to create the module object.

But importlib.import_module is a bit easier to use (especially for submodules) so that would be

foo = import_module('module').foo

If the attribute access also needs to be dynamic, you can use getattr, so

def from_module_get(module_name, attr):
    return getattr(import_module(module_name), attr)
>>> from_module_get('math', 'tau')
6.283185307179586

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...