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?
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.
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.
__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.
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())
.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With