Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to invoke a Python method using its fully qualified name?

In Java I can invoke a class or method without importing it by referencing its fully qualified name:

public class Example {
    void example() {

        //Use BigDecimal without importing it
        new java.math.BigDecimal(1);
    }
}

Similar syntax will obviously not work using Python:

class Example:
    def example(self):

        # Fails
        print(os.getcwd())

Good practice and PEP recommendations aside, can I do the same thing in Python?

like image 397
noamt Avatar asked Aug 30 '17 11:08

noamt


People also ask

What is qualified name in Python?

The __qualname__ attribute means qualified name in Python. It gives you a dotted path to the name of the target object. Using __qualname__ is useful with nested structures, such as when you have a method inside a class.

What is __ module __ in Python?

The __module__ property is intended for retrieving the module where the function was defined, either to read the source code or sometimes to re-import it in a script.

What is __ import __ in Python?

__import__() Parameters name - the name of the module you want to import. globals and locals - determines how to interpret name. fromlist - objects or submodules that should be imported by name. level - specifies whether to use absolute or relative imports.


3 Answers

A function does not exist until its definition runs, meaning the module it's in runs, meaning the module is imported (unless it's the script you ran directly).

The closest thing I can think of is print(__import__('os').getcwd()).

like image 97
Alex Hall Avatar answered Nov 24 '22 07:11

Alex Hall


No. If you want to use a module in Python, you must explicit import it's name into the scope. And, as @AlexHall mentioned, a class/function/module does not exist until import time. There's no way to accesses it without import-ing. In my opinion however, this makes for better and more explicit code. This forces you to be explicit when importing module names.

like image 35
Christian Dean Avatar answered Nov 24 '22 07:11

Christian Dean


Very late, but in case someone finds it useful, I've been using:

def fqn_import(fqn: str):
    module_name, _, function_name = fqn.rpartition('.')
    return getattr(importlib.import_module(module_name), function_name)
like image 32
VBobCat Avatar answered Nov 24 '22 07:11

VBobCat