Search code examples
pythonmethodsmoduleinvoke

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?


Solution

  • 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()).