Python module object import

Python Modules

Summary: in this tutorial, you’ll learn about Python modules, how to import objects from a module, and how to develop your modules.

Introduction to Python modules

A module is a piece of software that has a specific functionality. A Python module is a file that contains Python code.

For example, when building a shopping cart application, you can have one module for calculating prices and another module for managing items in the cart. Each module is a separate Python source code file.

A module has a name specified by the filename without the .py extension. For example, if you have a file called pricing.py , the module name is pricing .

Writing Python modules

First, create a new file called pricing.py and add the following code:

# pricing.py def get_net_price(price, tax_rate, discount=0): return price * (1 + tax_rate) * (1-discount) def get_tax(price, tax_rate=0): return price * tax_rateCode language: Python (python)

The pricing module has two functions that calculate the net price and tax from the selling price, tax rate, and discount.

Importing module objects

To use objects defined in a module from another file, you can use the import statement.

The import statement has several forms that we will discuss in the next sections.

1) import

To use objects defined in a module, you need to import the module using the following import statement:

import module_nameCode language: Python (python)

For example, to use the pricing module in the main.py file, you use the following statement:

import pricingCode language: Python (python)

When you import a module, Python executes all the code from the corresponding file. In this example, Python executes the code from the pricing.py file. Also, Python adds the module name to the current module.

This module name allows you to access functions, variables, etc. from the imported module in the current module. For example, you can call a function defined in the imported module using the following syntax:

module_name.function_name()Code language: Python (python)

The following shows how to use the get_net_price() function defined in the pricing module in the main.py file:

# main.py import pricing net_price = pricing.get_net_price( price=100, tax_rate=0.01 ) print(net_price)Code language: Python (python)
101.0Code language: Python (python)

2) import as new_name

If you don’t want to use the pricing as the identifier in the main.py , you can rename the module name to another as follows:

import pricing as selling_priceCode language: Python (python)

And then you can use the selling_price as the identifier in the main.py :

net_price = selling_price.get_net_price( price=100, tax_rate=0.01 )Code language: Python (python)

3) from import

Читайте также:  Javascript all in one page

If you want to reference objects in a module without prefixing the module name, you can explicitly import them using the following syntax:

from module_name import fn1, fn2Code language: Python (python)

Now, you can use the imported functions without specifying the module name like this:

fn1() fn2()Code language: Python (python)

This example imports the get_net_price() function from the pricing module:

# main.py from pricing import get_net_priceCode language: Python (python)

and use the get_net_price() function from the pricing module:

# main.py from pricing import get_net_price net_price = get_net_price(price=100, tax_rate=0.01) print(net_price)Code language: Python (python)

4) from import as : rename the imported objects

It’s possible to rename an imported name to another by using the following import statement:

from import as Code language: Python (python)

The following example renames the get_net_price() function from the pricing module to calculate_net_price() function:

from pricing import get_net_price as calculate_net_price net_price = calculate_net_price( price=100, tax_rate=0.1, discount=0.05 )Code language: Python (python)

5) from import * : import all objects from a module

To import every object from a module, you can use the following syntax:

from module_name import *Code language: Python (python)

This import statement will import all public identifiers including variables, constants, functions, classes, etc., to the program.

However, it’s not a good practice because if the imported modules have the same object, the object from the second module will override the first one. The program may not work as you would expect.

Let’s see the following example.

First, create a new file called product.py and define the get_tax() function:

# product.py def get_tax(price): return price * 0.1Code language: Python (python)

Both product and pricing modules have the get_tax() function. However, the get_tax() function from the product module has only one parameter while the get_tax() function from the pricing module has two parameters.

Читайте также:  User authorization in java

Second, import all objects from both pricing and product modules and use the get_tax() function:

from pricing import * from product import * tax = get_tax(100) print(tax)Code language: Python (python)

Since the get_tax() function from the product module overrides the get_tax () function from the pricing module, you get the tax with a value of 10.

Summary

  • A module is a Python source code file with the .py extension. The module name is the Python file name without the extension.
  • To use objects from a module, you import them using the import statement.

Источник

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 достаточно интересна, что позволяет ему иметь низкий порог вхождения, низкое время написания кода, высокую читаемость, но именно в ней и кроется подвох.

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

Читайте также:  Java object init null

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

Все просто, это любимый всеми программистами класс, использующий паттерн проектирования 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, поэтому часть примеров заведомо упрощена и нацелена на освещение существующих подходов.

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

Источник

Оцените статью