Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Module Initialization

Is it bad practice to initialize the objects in the module, in the module code?

in Module.py:

class _Foo(object):
    def __init__(self):
        self.x = 'Foo'

Foo = _Foo()

Than in user code, you could:

>>> from Module import Foo
>>> print Foo.x
'Foo'
>>>

...without having to initialize the Foo class in the user code. Of course, only useful if you don't need arguments to initialize the object.

Is there a reason not to do this?

like image 409
tMC Avatar asked Sep 13 '11 01:09

tMC


People also ask

How do I initialize a Python module?

Create the package directory – we can use terminal or Python IDE for this. Create __init__.py file – this is required to convert a normal directory into python package. This file is used to initialize the package and list all the modules. In the simplest form, this file can be empty.

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 does adding __ init __ py do?

The __init__.py file lets the Python interpreter know that a directory contains code for a Python module. An __init__.py file can be blank. Without one, you cannot import modules from another folder into your project. The role of the __init__.py file is similar to the __init__ function in a Python class.

How do you initialize a package?

If a file named __init__.py is present in a package directory, it is invoked when the package or a module in the package is imported. You can use this to execute package initialization code, for example for the initialization of package-level data.


1 Answers

Typically, you only want to run the minimum necessary to have your module usable. This will have an overall effect on performance (loading time), and can also make debugging easier.
Also, usually more than one instance will be created from any given class.

Having said that, if you have good reasons (such as only wanting one instance of a class), then certainly initialize it at load time.

like image 91
Ethan Furman Avatar answered Oct 02 '22 22:10

Ethan Furman