Python import, how and why?


What is import in Python?

In the Python programming language, packages and modules are connected using import. This allows code to be distributed across the application’s logical “nodes” (data models, handlers, etc.), which results in less code-heavy files.

Pros:

  • Increases the readability of the code.

  • The code is logically divided into “nodes”, its search and further error trapping becomes clearer and easier.

  • For development in a team, this gives a clearer understanding of what and where everyone does when performing a “task”.

Minuses:

How to use import?

The import syntax in Python is quite simple and intuitive:

# В данной строке импортируется something_we_want
import something_we_want 

# В данной строке импортируется something_we_want, как aww(логично и просто)
import something_we_want as aww 

# В данной строке импортируется из something_we_want something(логично и просто)
from something_we_want import something

# В данной строке импортируется из something_we_want something, как s(логично и просто)
from something_we_want import something as s

# Синтаксис as позволяет обращаться к импортируемому по новому нами описанному 
# далее имени(это работает только в рамках нашего файла)

What can be imported?

For a deeper understanding of import, consider the example below.

something_we_want.py:

def something():
    pass


somedata = 5

main.py:

# 1 случай
import something_we_want
something_we_want.something()

import something_we_want
print(something_we_want.somedata)

# 2 случай
import something_we_want as aww
aww.something()

import something_we_want as aww
print(aww.somedata)

# 3 случай
from something_we_want import something
something()

from something_we_want import somedata
print(somedata)

# 4 случай
from something_we_want import something as s
s()

from something_we_want import somedata as sd
print(sd)

# Классы импортируются по аналогии с функциями

Beautiful, readable and understandable.

What’s the catch?

But even in such a simple example, there is a catch that many do not know about (if you are a beginner programmer, then it is better to skip to the next table of contents).

The ideology of Python is quite interesting, which allows it to have a low entry threshold, low code writing time, high readability, but this is where the catch lies.

From my experience of using this language, there was a distinct feeling of the main idea of ​​OOP (everything is an object). What’s wrong with that?

All files, functions, etc. it’s an object. But what is this object and what is the class behind it?

It’s simple, this is a class beloved by all programmers that uses the Singleton design pattern.

Therefore, with a sufficiently branched structure, the import of a variable and its further modification can generate bugs that are not easy to understand (a variable can have any value in its life cycle and there are no guarantees).

Branching structure of the application and existing import approaches

Often in application development, programmers try to break down a program into logical “nodes”. This approach improves readability and allows you to develop in a team (one person implements one “node”, the second another). This is how the structure of the application is generated, which is often quite extensive (branched, because having one entry point from where, already acquiring functionality, it becomes like a tree).

An example of a branching structure:

There are 2 importing approaches (it’s better to choose one and stick with it for the whole project):

  1. Named

  2. unnamed

Named import example from models.py to auth.py:

# auth.py
from app.models import User

An example of an unnamed import from models.py to auth.py:

# auth.py
from ..models import User

# Количество точек указывает на сколько (обьектов) мы поднимаемся от исходного.
# В данном примере первая точка поднимает нас на уровень обьекта handlers,
# А вторая точка поднимает нас на уровень обьекта app

These are two completely different approaches. In the first case, we “go” from the “root” (the entry point of our application). In the second case, we “go” from the “sheet” (our file).

Pros and cons of import approaches:

Named

unnamed

pros

You can see the import and application structure.

High readability.

Part of the import structure is visible.

The programmer does not need to know the complete structure of the application.

The import is independent of the entry point.

The code becomes unattached to the application. Which essentially allows you to execute the code from anywhere (tests, separately, etc.). Improved adaptability. It becomes possible to develop individual application nodes without the full involvement of the programmer in the project.

Minuses

The import depends on the entry point.

The programmer needs to know the structure of the application. The code is strongly coupled to the application. Which essentially complicates debugging, testing, and so on. The programmer becomes heavily involved in the project.

Reduced readability of imports.

Although the first approach has significant disadvantages in use, it is nevertheless popular. It is more familiar to programmers, although it has drawbacks. And beginners often do not think about alternatives.

PS

This article was written for novice programmers who want to learn how to write in the Python programming language, so some of the examples are deliberately simplified and aimed at highlighting existing approaches.

Write the code that you yourself would like to receive from the performer.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *