1

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)

1
  • You always import the entire module. You can choose to only extract a name from the global namespace, they type of the object is irrelevant Commented Jan 22, 2021 at 4:16

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.