Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python module __init__ function

Is there any way to make an implicit initializer for modules (not packages)? Something like:

#file: mymodule.py
def __init__(val):
    global value
    value = 5

And when you import it:

#file: mainmodule.py
import mymodule(5)
like image 804
TulkinRB Avatar asked Mar 08 '15 10:03

TulkinRB


People also ask

What does __ init __ do in Python package?

The __init__ method is the Python equivalent of the C++ constructor in an object-oriented approach. The __init__ function is called every time an object is created from a class. The __init__ method lets the class initialize the object's attributes and serves no other purpose. It is only used within classes.

Why is __ init __ py module used in Python?

The __init__.py files are required to make Python treat directories containing the file as packages. This prevents directories with a common name, such as string , unintentionally hiding valid modules that occur later on the module search path.

What is __ module __ in Python?

A module in Python is a file (ending in .py ) that contains a set of definitions (variables and functions) that you can use when they are imported. Modules are considered as objects, just as everything else is in Python.

What does __ init __ py mean?

The __init__.py file indicates that the files in a folder are part of a Python package. Without an __init__.py file, you cannot import files from another directory in a Python project.


1 Answers

The import statement uses the builtin __import__ function.
Therefore it's not possible to have a module __init__ function.

You'll have to call it yourself:

import mymodule
mymodule.__init__(5)
like image 130
tynn Avatar answered Oct 18 '22 07:10

tynn