How to call a Python method using its full name?

In Java, I can call a class or method without importing it, referencing its full name:

public class Example { void example() { //Use BigDecimal without importing it new java.math.BigDecimal(1); } } 

A 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 in Python?

+5
source share
3 answers

A function does not exist until its definition is launched, that is, the module that it runs, that is, the module is imported (unless it starts the script).

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

+2
source

No. If you want to use the module in Python, you must explicitly import its name into the scope. And, as @AlexHall noted, the module / module / module does not exist until the moment of import. No access to it without import -ing. However, in my opinion, this provides better and more explicit code. This forces you to be explicit when importing module names.

+2
source

I'm not sure you can do the same, but you can only import the function:

 from foo.bar import baz as baz_fn baz_fn() 

where foo.bar is the fully qualified name of the module containing the function, and baz is the name of the function you want to import. It will import it as the name baz_fn .

+1
source

Source: https://habr.com/ru/post/1271362/


All Articles