如何将 python 模块创建为单个可调用函数?

How to create a python module as a single callable function?

我想将模块编写为函数而不是 class。

有没有办法让这项工作按预期进行?

greet.py
def main(x):
    print(f'Hello {x}!')

现在我该如何编写模块,以便在执行 greet 时,main 运行。

main.py
import greet

greet('Foo') # output: Hello Foo!

很遗憾,这是不可能的。

对象、class 或函数可以调用,但模块不能。

不过,您可以方便地命名:

[greet.py]
def greet(x):
     ...

[main.py]
    from greet import greet
    greet('foo')

不要这样做。如果你不确定你是否需要这个,你不需要。使模块可调用是一件非常奇怪的事情。然而,这是一种有趣的求知欲,所以...

可以做到这一点,利用模块本身就是一个对象这一事实,并且如果对象 class 具有 __call__ 方法,则该对象是可调用的。

但是,一个问题是module是一个内置的,你不能修改内置的属性。

因此,最简单的解决方案是创建一个 class 来代替 sys.modules 中的模块,但也有一个 __call__ 方法。

greet.py中:

import sys

class CallableModule():

    def __init__(self, wrapped):
        self._wrapped = wrapped

    def __call__(self, *args, **kwargs):
        return self._wrapped.main(*args, **kwargs)

    def __getattr__(self, attr):
        return object.__getattribute__(self._wrapped, attr)

sys.modules[__name__] = CallableModule(sys.modules[__name__])

def main(x):
    print(f'Hello {x}!')

来自shell:

>>> import greet
>>> greet('there')
Hello there!