WobbaFetttttt
WobbaFetttttt

Reputation: 73

Can I make a Python Module __init__.py callable?

The documentation for __init__.py is quite hard to find. I can't find a place that explains all the things you can do in this file. The Python module documentation barely even mentions __init__.py nor that you can use __all__ for from module import *

What I want is for my module to be callable like:

main.py

import module

module()

module/__ init __.py

def __call__(self):    # self here cause modules are loaded as objects?
    print 'callable'

Upvotes: 1

Views: 1842

Answers (1)

Artem Kryvonis
Artem Kryvonis

Reputation: 128

Maybe silly answer but you can add method into __init__.py file like

__init__.py

def module():
    # what functions do you need to run into __init__ file

and then

main.py

from module import module
module()

also, you just can write some operations into init and then it will be calling after import

example:

__init__.py

print('1')
print('2')
print('3')

main.py

import module

after run main.py the output will be

1
2
3

but actually, it's not good practice. Try to write code without "calling" modules because a module is a file containing Python definitions and statements, not the function that needs to call.

Upvotes: 1

Related Questions