Python ways to import

4 ways to import a module in Python

Sign in to your Python Morsels account to save your screencast settings.

Let’s talk about the four ways to import something from a module in Python.

Importing the whole module object

The first way is to use the import statement, using the syntax import module_name :

We’ve just imported the math module. We can use the things within this module by looking up attributes on the math module object. For example, we can get the square root of a number by calling math.sqrt :

Or we can access the number π with math.pi :

But we can’t access just pi or sqrt (without that math. prefix):

>>> pi Traceback (most recent call last): File "", line 1, in NameError: name 'pi' is not defined >>> sqrt(25) Traceback (most recent call last): File "", line 1, in NameError: name 'sqrt' is not defined >>> 

The reason is, when we import a module using that import module_name syntax, we get just one thing: a variable that points to a module object.

Everything in that module is accessible as an attribute on that module object:

Importing specific things from a module

If you wanted to just type pi instead of math.pi , you could use the from syntax for importing:

>>> from math import pi >>> pi 3.141592653589793 

So now we have pi , but not sqrt (because we didn’t import it):

>>> sqrt(25) Traceback (most recent call last): File "", line 1, in NameError: name 'sqrt' is not defined 

And we don’t have access to the whole math module:

>>> math Traceback (most recent call last): File "", line 1, in NameError: name 'math' is not defined 

If you want to import multiple things from a module using this from syntax, you could put commas each thing you’d like to import:

>>> from math import pi, sqrt >>> pi 3.141592653589793 >>> sqrt(25) 5.0 

That from math import pi, sqrt line plucks out pi and sqrt from the math module, but nothing else.

Avoiding name collision when importing

If you use the from syntax to grab specific things from a module and you grab something of the same name from two different modules, you’re in for trouble.

Here we’re importing sqrt from the math module and sqrt from the cmath module ( cmath is for complex numbers):

>>> from math import sqrt >>> from cmath import sqrt 

The sqrt function we end up with came from the cmath module:

We imported two different functions named sqrt and the last one won. We first got sqrt from the math module and then we overwrote our local sqrt variable with the sqrt function from the cmath module.

To fix this we could rename sqrt from the cmath module as we import it, by using the as syntax:

>>> from math import sqrt >>> from cmath import sqrt as csqrt 

So, sqrt is now the sqrt function from the math module and csqrt is the one from the cmath module:

If you look at the function the csqrt variable points to, you’ll even see that it’s actually called sqrt :

We pointed our local variable csqrt to the sqrt function within the cmath module.

Importing a module under a different name

You can also use the as syntax when importing a whole module.

The variable m now points to the math module object which means we can’t say math.pi anymore:

>>> math.pi Traceback (most recent call last): File "", line 1, in NameError: name 'math' is not defined 

Instead we can use m.pi or m.sqrt :

>>> m.pi 3.141592653589793 >>> m.sqrt(25) 5.0 

You likely won’t see this convention used often except in specific Python communities where it’s commonplace.

For example, in the Pandas world people often import pandas as pd :

And in the NumPy world, people often import numpy as np :

It’s not very common to see module names shortened using the as syntax, except in areas where it’s conventional (like Pandas and NumPy).

Trey says: If I saw m.pi in your code, I’d probably find it a little bit odd.

The 4 ways to import a module

So there’s four different ways to import:

  1. Import the whole module using its original name: import random
  2. Import specific things from the module: from random import choice, randint
  3. Import the whole module and rename it, usually using a shorter variable name: import pandas as pd
  4. Import specific things from the module and rename them as you’re importing them: from os.path import join as join_path

That last one is usually done to avoid a name collision or sometimes to make a more descriptive name (though that’s not very common).

Trey’s recommendations

  1. Use from for short and descriptive variable names I tend to use the from syntax most (number 2 above) because I prefer short and descriptive variable names.
  2. Import the whole module if needed to avoid ambiguity. If there’s a name like choice that isn’t as clear as random.choice , then I prefer to import the whole module for a more descriptive name
  3. Avoid renaming imports. I very rarely use the as syntax (unless I’m in the pandas or numpy worlds, where it’s common convention). And I almost never use the as syntax with from unless I’m avoiding a name collision.

What comes after Intro to Python?

Intro to Python courses often skip over some fundamental Python concepts.

Sign up below and I’ll explain concepts that new Python programmers often overlook.

Series: Modules

Modules are the tool we use for breaking up our code into multiple files in Python. When you write a .py file, you’re making a Python module. You can import your own modules, modules included in the Python standard library, or modules in third-party packages.

To track your progress on this Python Morsels topic trail, sign in or sign up.

Источник

Python import, как и для чего?

В языке программирования Python подключение пакетов и модулей осуществляется с помощью import. Это позволяет распределять код по логическим «узлам» приложения(модели данных, обработчики, и тп.), что позволяет получить менее нагруженные кодом файлы.

  • Повышается читаемость кода.
  • Код логически разбит по «узлам», его поиск и дальнейший отлов ошибок становится понятнее и проще.
  • Для разработки в команде это дает более четкое понимание, что и где делает каждый при выполнении «задания».

Как использовать import?

Синтаксис import в Python достаточно прост и интуитивно понятен:

# В данной строке импортируется 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 позволяет обращаться к импортируемому по новому нами описанному # далее имени(это работает только в рамках нашего файла)

Что можно импортировать?

Для более глубокого понимания import стоит рассмотреть пример, представленный ниже.

def something(): pass somedata = 5
# 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) # Классы импортируются по аналогии с функциями

Красиво, читаемо и понятно.

В чем же подвох?

Но даже в таком простом примере есть подвох, о котором многие не догадываются(если вы начинающий программист, то лучше перейдите к следующему оглавлению).

Идеология Python достаточно интересна, что позволяет ему иметь низкий порог вхождения, низкое время написания кода, высокую читаемость, но именно в ней и кроется подвох.

По своему опыту использования данного языка, сложилось отчетливое ощущение главной идеи ООП(все есть объект). Что же в этом плохого?

Все файлы, функции и тд. это объект. Но что это за объект и класс стоят за файлами(модулями)?

Все просто, это любимый всеми программистами класс, использующий паттерн проектирования Singleton.

Поэтому при достаточно ветвистой структуре, импорт переменной и дальнейшая ее модификация может порождать достаточно не простые в понимании баги(переменная в своем цикле жизни может иметь любое значение и никаких гарантий нет).

Ветвистая структура приложения и существующие подходы импортирования

Часто в разработке приложений программисты пытаются разбить программу по логическим «узлам». Данный подход повышает читаемость и позволяет вести разработку в команде(один человек занимается реализацией одного «узла», второй другого). Так порождается структура приложения, которая зачастую виду сложности функционала является достаточно обширной(ветвистой, потому что имея одну точку входа откуда уже обрастая функционалом это становится похожим на дерево).

Пример ветвистой структуры:

Существует 2 подхода импортирования(лучше выбрать один и придерживаться его весь проект):

Пример именованного импорта из models.py в auth.py:

# auth.py from app.models import User

Пример неименованного импорта из models.py в auth.py:

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

Это два абсолютно разных подхода. В первом случае мы «идем» из «корня»(входной точки нашего приложения). Во втором случае мы «идем» от «листа»(нашего файла).

Плюсы и минусы подходов импорта:

Видна структура импорта и приложения.

Видна часть структуры импорта.

Программисту не нужно знать полную структуру приложения.

Импорт не зависит от точки входа.

Код становится не привязанным к приложению. Что по сути позволяет исполнить код из любой точки(тесты, отдельно и тд.). Повышается отлаживаемость. Появляется возможность разработки отдельных узлов приложения без полного вовлечения программиста в проект.

Импорт зависит от точки входа.

Программисту необходимо знать структуру приложения. Код сильно связан с приложением. Что по сути усложняет отладку, тестирование, и тд. Программист становится сильно вовлеченным в проект.

Снижается читаемость импорта.

Хоть первый подход и имеет существенные минусы в использовании, но тем не менее он популярен. Программистам он привычнее, хоть и имеет недостатки. А начинающие часто не задумываются об альтернативах.

P.S.

Данная статья была написана для начинающих программистов, которые хотят научиться писать на языке программирования Python, поэтому часть примеров заведомо упрощена и нацелена на освещение существующих подходов.

Пишите тот код, который бы сами хотели получить от исполнителя.

Источник

Читайте также:  Java class user example
Оцените статью