I'm writing a module called foo
that has many internal functions, but ultimately boils down to a single external function foo()
. When using this module/function, I'd like to do
import foo
foo(whatever)
instead of
from foo import foo
foo(whatever)
Is this possible?
In the __init__.py file of a package __all__ is a list of strings with the names of public modules or other objects. Those features are available to wildcard imports. As with modules, __all__ customizes the * when wildcard-importing from the package.
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.
By module. exports, we can export functions, objects, and their references from one file and can use them in other files by importing them by require() method.
You could monkey patch the sys.modules
dictionary to make the name of your module point to the function instead of your module.
foo.py
(the file defining your module foo
) would look like this
import sys
def foo(x):
return x + x
sys.modules[__name__] = foo
then you can use this module from a different file like this
import foo
print(foo(3))
6
There are probably reasons for why you shouldn't do this. sys.modules
isn't supposed to point to functions, when you do from some_module import some_function
, the module some_module
is what gets added to sys.modules
, not the function some_function
.
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