Search code examples
pythonpython-3.xmodulepython-module

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


I'd like to write the module as a function and not a class.

Is there a way to make this work as intended?

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

Now how do I write the module so that when greet is executed, main runs.

main.py
import greet

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

Solution

  • Unfortunately, this isn't possible.

    An object, class, or function can be callable, but a module cannot.

    You can, however, name things conveniently:

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