Skip to content

Imports, __init__.py files, and SpyDrNet Extensions

jacobdbrown4 edited this page Dec 3, 2021 · 5 revisions

Importing

Two methods of importing classes are discussed in the following.

Method One

To import a class found in another module, one can specify the module and import the class by doing the following:

from <path_to_python_module> import <class_object_inside_the_module>

So to import a class object in SpyDrNet, one can do the following:

spydrnet.ir.**module** import **class**

See this line in the SpyDrNet repo for an example. This imports the Element class straight from the Element module found in the spydrnet/ir directory.

Method Two

On the other hand, one can also specify the directory in which the class is defined. Like this:

from <path_to_directory> import <class_object_inside_a_module_in_the_directory>

So in SpyDrNet it would be:

spydrnet.ir import **class**

See this line for an example. This imports the Element class from the IR directory. The __init__.py file in the directory makes this possible.

What is the __init__.py file?

“The __init__.py file lets the Python interpreter know that a directory contains code for a Python module...The role of the __init__.py file is similar to the __init__ function in a Python class. The file is essentially the constructor of your package or directory without it being called such. It sets up how packages or functions will be imported into your other files.” Source: Career Karma

See this article for the whole description.

Also, the Python documentation says:

"The import statement first tests whether the item is defined in the package; if not, it assumes it is a module and attempts to load it."

So when someone tries to import something from a directory, items defined (by the __init__.py file) take precedence over modules with the same name that may also be present in the directory. For example:

from spydrnet.ir import Element

will return the Element class, and not the element.py module itself.

Importing with SpyDrNet's Extension System

With the new extension system, the __init__.py file inside of the IR directory is used to handle extending the classes. When one imports a class using

from spydrnet.ir import **class**

the imported class is the one made discoverable by the __init__.py file. But before it returns the class, the functions in __init__.py look for other available plugins to extend it. This is how we obtain the extended class. If one imports it using the first method, they will get the normal, unextended version straight from the module’s code.

Clone this wiki locally