Reputation: 7835
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?
Upvotes: 7
Views: 1367
Reputation: 2732
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)
Upvotes: 2
Reputation: 36043
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())
.
Upvotes: 4
Reputation: 22973
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.
Upvotes: 2
Reputation: 523
I'm not sure that you can do exactly the same, but you can import only the function:
from foo.bar import baz as baz_fn
baz_fn()
where foo.bar
is the fully qualified name of the module that contains the function and baz
is the name of the function you wish to import. It will import it as the name baz_fn
.
Upvotes: 1