From c7d402b845c6de3213d607e9de764b7c17520ceb Mon Sep 17 00:00:00 2001 From: Kirill Mokevnin Date: Sat, 7 Nov 2026 19:18:42 -0500 Subject: [PATCH] =?UTF-8?q?fix(packages):=20=D0=B7=D0=B0=D0=BA=D1=80=D0=B5?= =?UTF-8?q?=D0=BF=D0=BB=D1=8F=D1=82=D1=8C=20=D0=B8=D0=BC=D0=BF=D0=BE=D1=80?= =?UTF-8?q?=D1=82=20=D0=BF=D0=B0=D0=BA=D0=B5=D1=82=D0=B0=20=D0=B2=20=D0=BF?= =?UTF-8?q?=D1=80=D0=B0=D0=BA=D1=82=D0=B8=D0=BA=D0=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Refs: CONTENT-784 --- .../400-packages/en/EXERCISE.md | 20 +++++---- .../400-packages/en/README.md | 25 ++++++++--- .../400-packages/es/EXERCISE.md | 20 +++++---- .../400-packages/es/README.md | 21 ++++++--- .../400-packages/ru/EXERCISE.md | 20 +++++---- .../400-packages/ru/README.md | 21 ++++++--- .../400-packages/solution.py | 10 ++--- .../400-packages/test_solution.py | 44 +++++++++++++------ 8 files changed, 118 insertions(+), 63 deletions(-) diff --git a/modules/40-define-functions/400-packages/en/EXERCISE.md b/modules/40-define-functions/400-packages/en/EXERCISE.md index 1b3301a6..c1ad5953 100644 --- a/modules/40-define-functions/400-packages/en/EXERCISE.md +++ b/modules/40-define-functions/400-packages/en/EXERCISE.md @@ -1,14 +1,18 @@ -Implement the function `generate_pin()`. It returns a random four-digit PIN code as a string. +A message can contain the characters `<`, `>` and `&`. When displayed on an HTML page, a browser can interpret them as markup. The standard-library package `html` replaces these characters with special sequences to preserve the message text. -Each digit of the PIN is an independent random integer from 0 to 9. +## Task + +Implement the function `escape_html(text)`. It takes a string and returns the result of the `escape()` function from the `html` package with its default arguments. Single and double quotes are also replaced. ```python -print(generate_pin()) # => e.g. "4823" or "0571" -print(generate_pin()) # => e.g. "1942" or "0037" +print(escape_html("A & B")) # => <b>A & B</b> +print(escape_html('"Hello"')) # => "Hello" +print(escape_html("It's ok")) # => It's ok +print(escape_html("Hello")) # => Hello ``` -Add a return type annotation. - -## Hint +## Hints -Generate each of the four digits with `random.randint(0, 9)` and combine them into a string using an f-string. +- `html` is a regular package in the standard library. Its _\_\_init\_\_.py_ file provides the `escape()` function +- Import the package with `import html` or the function with `from html import escape` +- [html.escape documentation](https://docs.python.org/3/library/html.html#html.escape) diff --git a/modules/40-define-functions/400-packages/en/README.md b/modules/40-define-functions/400-packages/en/README.md index e518ba4d..523de7eb 100644 --- a/modules/40-define-functions/400-packages/en/README.md +++ b/modules/40-define-functions/400-packages/en/README.md @@ -1,10 +1,10 @@ Python programs almost always use code written by others. Reinventing mathematical functions, date handling, or network requests makes no sense — all of this is already available. Python uses packages to share and reuse code. -A package is a directory of Python files organized by topic. The Python standard library contains dozens of such packages, covering everything from mathematics to filesystem access. +A regular package is a directory containing an _\_\_init\_\_.py_ file and Python modules organized by topic. The _\_\_init\_\_.py_ file can be empty. A directory can hold any files; this file identifies it as a regular Python package. The standard library provides both individual modules and packages. -## Importing a Package +## Importing Modules and Packages -To use code from a package, import it with the `import` keyword. Let's look at the `math` package: +To use code from a package, import it with the `import` keyword. Let's look at the `math` module: ```python import math @@ -13,7 +13,7 @@ print(math.sqrt(16)) # => 4.0 print(math.pi) # => 3.141592653589793 ``` -After `import math`, everything in the package is available through dot notation: `math.sqrt`, `math.floor`, `math.pi`. +After `import math`, its names are available through dot notation: `math.sqrt`, `math.floor`, `math.pi`. ## Importing Specific Names @@ -42,7 +42,7 @@ An alias is useful when a name conflicts with an existing variable or is simply ## Standard Library -Python ships with a rich set of built-in packages. A few commonly used ones: +Python ships with a rich set of modules and packages. A few commonly used modules: - `math` — mathematical functions: `sqrt`, `hypot`, `floor`, `ceil`, `pi` - `random` — random numbers: `randint`, `choice`, `shuffle` @@ -55,6 +55,21 @@ print(random.randint(1, 6)) # => random number from 1 to 6 print(random.choice(["rock", "paper", "scissors"])) # => random element ``` +## Creating a Regular Package + +A package groups related modules under one import path. A project with payment modules can have this structure. + +```text +payments/ +├── __init__.py +├── stripe.py +└── paypal.py +``` + +The _\_\_init\_\_.py_ file belongs to the package, while _stripe.py_ and _paypal.py_ are its modules. Importing `payments.stripe` gives access through `payments.stripe`; `from payments import stripe` binds the same module to the shorter name `stripe`. Importing `payments` executes _\_\_init\_\_.py_, which may define names available through the package. This file stays empty when no initialization code is needed. + +Python also supports namespace packages, which can combine portions from several directories without _\_\_init\_\_.py_. The packages created in this lesson are regular packages and include that file in every package directory. + ## Third-Party Packages Beyond the standard library, thousands of packages are created by developers around the world. Install them with `pip`, Python's package manager: diff --git a/modules/40-define-functions/400-packages/es/EXERCISE.md b/modules/40-define-functions/400-packages/es/EXERCISE.md index da4ba229..eceb607d 100644 --- a/modules/40-define-functions/400-packages/es/EXERCISE.md +++ b/modules/40-define-functions/400-packages/es/EXERCISE.md @@ -1,14 +1,18 @@ -Implementa la función `generate_pin()`. Devuelve un código PIN de cuatro dígitos aleatorio como cadena de texto. +Un mensaje puede contener los caracteres `<`, `>` y `&`. Al mostrarlo en una página HTML, el navegador puede interpretarlos como parte del marcado. El paquete `html` de la biblioteca estándar los sustituye por secuencias especiales para conservar el texto del mensaje. -Cada dígito del PIN es un entero aleatorio independiente del 0 al 9. +## Tarea + +Implementa la función `escape_html(text)`. Recibe una cadena y devuelve el resultado de `escape()` del paquete `html` con sus parámetros por defecto. También se sustituyen las comillas simples y dobles. ```python -print(generate_pin()) # => por ejemplo, "4823" o "0571" -print(generate_pin()) # => por ejemplo, "1942" o "0037" +print(escape_html("A & B")) # => <b>A & B</b> +print(escape_html('"Hello"')) # => "Hello" +print(escape_html("It's ok")) # => It's ok +print(escape_html("Hello")) # => Hello ``` -Añade la anotación de tipo del valor de retorno. - -## Pista +## Pistas -Genera cada uno de los cuatro dígitos con `random.randint(0, 9)` y combínalos en una cadena usando un f-string. +- `html` es un paquete regular de la biblioteca estándar. Su archivo _\_\_init\_\_.py_ proporciona la función `escape()` +- Puedes importar el paquete mediante `import html` o la función mediante `from html import escape` +- [Documentación de html.escape](https://docs.python.org/3/library/html.html#html.escape) diff --git a/modules/40-define-functions/400-packages/es/README.md b/modules/40-define-functions/400-packages/es/README.md index 21150ff8..3589757c 100644 --- a/modules/40-define-functions/400-packages/es/README.md +++ b/modules/40-define-functions/400-packages/es/README.md @@ -1,6 +1,6 @@ A medida que el programa crece aumenta no solo la cantidad de líneas de código, sino también la cantidad de módulos. En proyectos pequeños, decenas de archivos todavía se pueden mantener en un solo directorio, pero en aplicaciones reales los archivos pueden ser cientos y miles. -Para organizar los módulos en grupos lógicos más grandes, en Python se usan los paquetes. Un paquete es un directorio con archivos de Python. +Para organizar los módulos en grupos lógicos más grandes, en Python se usan los paquetes. En esta lección trabajamos con paquetes regulares. Un paquete regular es un directorio con un archivo _\_\_init\_\_.py_ y módulos de Python. El archivo _\_\_init\_\_.py_ puede estar vacío. Por ejemplo, la estructura de un proyecto puede verse así: @@ -8,9 +8,11 @@ Por ejemplo, la estructura de un proyecto puede verse así: project/ ├── main.py ├── payments/ +│ ├── __init__.py │ ├── stripe.py │ └── paypal.py └── users/ + ├── __init__.py ├── auth.py └── profile.py ``` @@ -39,7 +41,7 @@ El punto muestra el camino dentro del paquete. Python pasa secuencialmente del p ## Importación de un módulo concreto -A menudo no se importa todo el camino, sino un módulo concreto: +Las dos formas importan el módulo `payments.stripe`. La forma `from payments import stripe` lo asocia al nombre corto `stripe` en el archivo actual. ```python from payments import stripe @@ -47,7 +49,7 @@ from payments import stripe stripe.create_payment() ``` -Esa forma acorta la escritura y hace el código más compacto. +Lo que se acorta es la llamada, `stripe.create_payment()` en lugar de `payments.stripe.create_payment()`. La instrucción de importación puede ser más larga. ## Paquetes anidados @@ -56,8 +58,11 @@ Los paquetes pueden contener otros paquetes: ```text project/ └── app/ + ├── __init__.py └── payments/ + ├── __init__.py ├── stripe/ + │ ├── __init__.py │ ├── client.py │ └── api.py └── paypal.py @@ -80,8 +85,10 @@ Por ejemplo: ```text project/ ├── admin/ +│ ├── __init__.py │ └── config.py └── user/ + ├── __init__.py └── config.py ``` @@ -96,9 +103,9 @@ import user.config Sin los paquetes, esos nombres entrarían en conflicto entre sí. -## El archivo \_\_init\_\_.py +## El archivo de inicialización del paquete -Antes, para crear un paquete, dentro del directorio se colocaba obligatoriamente el archivo `__init__.py`: +El archivo _\_\_init\_\_.py_ identifica un paquete regular. También se crea cuando el paquete no necesita código común. En ese caso se deja vacío. ```text payments/ @@ -107,6 +114,6 @@ payments/ └── paypal.py ``` -Ese archivo informaba a Python de que el directorio había que tratarlo como un paquete. +Un directorio puede contener cualquier tipo de archivo. Con _\_\_init\_\_.py_, `payments` es un paquete regular cuyos módulos se importan como `payments.stripe` y `payments.paypal`. Al importar `payments`, Python ejecuta el código de _\_\_init\_\_.py_. Allí se pueden definir los nombres accesibles mediante el paquete. -En las versiones modernas de Python los paquetes pueden funcionar también sin `__init__.py`. No obstante, ese archivo se sigue usando a menudo. Normalmente en él se coloca código común y la configuración del paquete. +Python también tiene paquetes de espacio de nombres. Permiten reunir partes de un paquete desde varios directorios y no llevan _\_\_init\_\_.py_. Son otra forma de organizar paquetes. Los ejemplos de esta lección usan paquetes regulares y cada directorio de paquete, incluidos los anidados, contiene ese archivo. diff --git a/modules/40-define-functions/400-packages/ru/EXERCISE.md b/modules/40-define-functions/400-packages/ru/EXERCISE.md index 3d7f9df6..dfcdb54d 100644 --- a/modules/40-define-functions/400-packages/ru/EXERCISE.md +++ b/modules/40-define-functions/400-packages/ru/EXERCISE.md @@ -1,14 +1,18 @@ -Реализуйте функцию `generate_pin()`. Она возвращает случайный четырёхзначный PIN-код в виде строки. +Текст сообщения может содержать символы `<`, `>` и `&`. При выводе на HTML-странице браузер воспринимает их как часть разметки. Пакет стандартной библиотеки `html` заменяет такие символы специальными последовательностями и сохраняет текст сообщения. -Каждый разряд PIN-кода — независимое случайное целое число от 0 до 9. +## Задание + +Реализуйте функцию `escape_html(text)`. Она принимает строку и возвращает результат функции `escape()` из пакета `html` с параметрами по умолчанию. При этом также заменяются одинарные и двойные кавычки. ```python -print(generate_pin()) # => например, "4823" или "0571" -print(generate_pin()) # => например, "1942" или "0037" +print(escape_html("A & B")) # => <b>A & B</b> +print(escape_html('"Hello"')) # => "Hello" +print(escape_html("It's ok")) # => It's ok +print(escape_html("Hello")) # => Hello ``` -Укажите аннотацию типа возвращаемого значения. - -## Подсказка +## Подсказки -Сгенерируйте каждую из четырёх цифр через `random.randint(0, 9)` и соберите строку через f-строку. Модуль `random` подключается в начале файла инструкцией `import random`, и после неё функция вызывается через имя модуля, `random.randint()`. +- `html` является обычным пакетом стандартной библиотеки. Его файл _\_\_init\_\_.py_ предоставляет функцию `escape()` +- Можно импортировать пакет через `import html` или саму функцию через `from html import escape` +- [Документация html.escape](https://docs.python.org/3/library/html.html#html.escape) diff --git a/modules/40-define-functions/400-packages/ru/README.md b/modules/40-define-functions/400-packages/ru/README.md index e8e62cbe..b599cc62 100644 --- a/modules/40-define-functions/400-packages/ru/README.md +++ b/modules/40-define-functions/400-packages/ru/README.md @@ -1,6 +1,6 @@ По мере роста программы увеличивается не только количество строк кода, но и количество модулей. В небольших проектах десятки файлов еще можно держать в одной директории, но в реальных приложениях файлов могут быть сотни и тысячи. -Чтобы организовывать модули в более крупные логические группы, в Python используют пакеты. Пакет представляет собой директорию с Python-файлами. +Чтобы организовывать модули в более крупные логические группы, в Python используют пакеты. В этом уроке мы работаем с обычными пакетами. Обычный пакет представляет собой директорию с файлом _\_\_init\_\_.py_ и модулями Python. Файл _\_\_init\_\_.py_ может быть пустым. Например, структура проекта может выглядеть так: @@ -8,9 +8,11 @@ project/ ├── main.py ├── payments/ +│ ├── __init__.py │ ├── stripe.py │ └── paypal.py └── users/ + ├── __init__.py ├── auth.py └── profile.py ``` @@ -39,7 +41,7 @@ payments.stripe.create_payment() ## Импорт конкретного модуля -Часто импортируют не весь путь, а конкретный модуль: +Обе формы импорта загружают модуль `payments.stripe`. Форма `from payments import stripe` связывает его с коротким именем `stripe` в текущем файле. ```python from payments import stripe @@ -47,7 +49,7 @@ from payments import stripe stripe.create_payment() ``` -Такой способ сокращает запись и делает код компактнее. +Сокращается обращение к функции, `stripe.create_payment()` вместо `payments.stripe.create_payment()`. Сам импорт при этом может занимать больше символов. ## Вложенные пакеты @@ -56,8 +58,11 @@ stripe.create_payment() ```text project/ └── app/ + ├── __init__.py └── payments/ + ├── __init__.py ├── stripe/ + │ ├── __init__.py │ ├── client.py │ └── api.py └── paypal.py @@ -80,8 +85,10 @@ from app.payments.stripe import client ```text project/ ├── admin/ +│ ├── __init__.py │ └── config.py └── user/ + ├── __init__.py └── config.py ``` @@ -96,9 +103,9 @@ import user.config Без пакетов такие имена конфликтовали бы между собой. -## Файл \_\_init\_\_.py +## Файл инициализации пакета -Раньше для создания пакета внутри директории обязательно размещали файл `__init__.py`: +Файл _\_\_init\_\_.py_ обозначает обычный пакет. Он нужен и тогда, когда внутри нет общего кода. В этом случае файл оставляют пустым. ```text payments/ @@ -107,9 +114,9 @@ payments/ └── paypal.py ``` -Этот файл сообщал Python, что директорию нужно воспринимать как пакет. +Каталог может хранить любые файлы. Наличие _\_\_init\_\_.py_ делает `payments` обычным пакетом, к модулям которого обращаются по именам `payments.stripe` и `payments.paypal`. При импорте `payments` Python выполняет код из _\_\_init\_\_.py_. В нём можно определить имена, доступные через пакет. -В современных версиях Python пакеты могут работать и без `__init__.py`. Тем не менее этот файл до сих пор часто используется. Обычно в нем размещают общий код и настройки пакета. +У Python также есть namespace-пакеты. Они позволяют объединять части одного пакета из нескольких каталогов и обходятся без _\_\_init\_\_.py_. Это отдельный способ организации пакетов. Для обычных пакетов из примеров этого урока файл создаётся в каждом каталоге пакета, в том числе во вложенных. ## Имена пакета в \_\_init\_\_.py diff --git a/modules/40-define-functions/400-packages/solution.py b/modules/40-define-functions/400-packages/solution.py index 62f13add..92d6c1df 100644 --- a/modules/40-define-functions/400-packages/solution.py +++ b/modules/40-define-functions/400-packages/solution.py @@ -1,9 +1,5 @@ -import random +import html -def generate_pin() -> str: - d1 = random.randint(0, 9) - d2 = random.randint(0, 9) - d3 = random.randint(0, 9) - d4 = random.randint(0, 9) - return f"{d1}{d2}{d3}{d4}" +def escape_html(text): + return html.escape(text) diff --git a/modules/40-define-functions/400-packages/test_solution.py b/modules/40-define-functions/400-packages/test_solution.py index d8eafb26..757aa80e 100644 --- a/modules/40-define-functions/400-packages/test_solution.py +++ b/modules/40-define-functions/400-packages/test_solution.py @@ -1,18 +1,36 @@ -import random +import importlib +from unittest.mock import patch + import solution def test(): - annotations = solution.generate_pin.__annotations__ - assert 'return' in annotations, "You should add a return type annotation" + assert callable(getattr(solution, "escape_html", None)), ( + "Define the escape_html(text) function" + ) + cases = [ + ("", ""), + ("Hello", "Hello"), + ("A & B", "<b>A & B</b>"), + ('"Hello"', ""Hello""), + ("It's ok", "It's ok"), + ("<", "&lt;"), + ("Привет, мир!", "Привет, мир!"), + ] + for text, expected in cases: + assert solution.escape_html(text) == expected, ( + "escape_html must return the escaped string", + text, + ) - for seed in [1, 7, 42]: - random.seed(seed) - result = solution.generate_pin() - random.seed(seed) - d1 = random.randint(0, 9) - d2 = random.randint(0, 9) - d3 = random.randint(0, 9) - d4 = random.randint(0, 9) - assert result == f"{d1}{d2}{d3}{d4}" - assert len(result) == 4 + with patch("html.escape", return_value="escaped-by-html") as escape: + importlib.reload(solution) + assert solution.escape_html("source") == "escaped-by-html", ( + "Use the escape function from the html package" + ) + assert escape.call_count == 1, "Use the escape function from the html package" + args, kwargs = escape.call_args + assert (args[0] if args else kwargs.get("s")) == "source", ( + "Use the escape function from the html package" + ) + importlib.reload(solution)