How do I export a single function as a module in Python?
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
.