Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I export a single function as a module in Python? [duplicate]

Tags:

python

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?

like image 519
Boris Avatar asked May 16 '18 03:05

Boris


People also ask

What does __ all __ mean in Python?

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.

What is __ module __?

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.

What can you export with module exports?

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.


1 Answers

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.

like image 193
Boris Avatar answered Oct 18 '22 03:10

Boris