Перейти к содержимому

Что такое библиотеки в python

  • автор:

Introduction¶

The “Python library” contains several different kinds of components.

It contains data types that would normally be considered part of the “core” of a language, such as numbers and lists. For these types, the Python language core defines the form of literals and places some constraints on their semantics, but does not fully define the semantics. (On the other hand, the language core does define syntactic properties like the spelling and priorities of operators.)

The library also contains built-in functions and exceptions — objects that can be used by all Python code without the need of an import statement. Some of these are defined by the core language, but many are not essential for the core semantics and are only described here.

The bulk of the library, however, consists of a collection of modules. There are many ways to dissect this collection. Some modules are written in C and built in to the Python interpreter; others are written in Python and imported in source form. Some modules provide interfaces that are highly specific to Python, like printing a stack trace; some provide interfaces that are specific to particular operating systems, such as access to specific hardware; others provide interfaces that are specific to a particular application domain, like the World Wide Web. Some modules are available in all versions and ports of Python; others are only available when the underlying system supports or requires them; yet others are available only when a particular configuration option was chosen at the time when Python was compiled and installed.

This manual is organized “from the inside out:” it first describes the built-in functions, data types and exceptions, and finally the modules, grouped in chapters of related modules.

This means that if you start reading this manual from the start, and skip to the next chapter when you get bored, you will get a reasonable overview of the available modules and application areas that are supported by the Python library. Of course, you don’t have to read it like a novel — you can also browse the table of contents (in front of the manual), or look for a specific function, module or term in the index (in the back). And finally, if you enjoy learning about random subjects, you choose a random page number (see module random ) and read a section or two. Regardless of the order in which you read the sections of this manual, it helps to start with chapter Built-in Functions , as the remainder of the manual assumes familiarity with this material.

Let the show begin!

Notes on availability¶

An “Availability: Unix” note means that this function is commonly found on Unix systems. It does not make any claims about its existence on a specific operating system.

If not separately noted, all functions that claim “Availability: Unix” are supported on macOS, which builds on a Unix core.

If an availability note contains both a minimum Kernel version and a minimum libc version, then both conditions must hold. For example a feature with note Availability: Linux >= 3.17 with glibc >= 2.27 requires both Linux 3.17 or newer and glibc 2.27 or newer.

WebAssembly platforms¶

The WebAssembly platforms wasm32-emscripten (Emscripten) and wasm32-wasi (WASI) provide a subset of POSIX APIs. WebAssembly runtimes and browsers are sandboxed and have limited access to the host and external resources. Any Python standard library module that uses processes, threading, networking, signals, or other forms of inter-process communication (IPC), is either not available or may not work as on other Unix-like systems. File I/O, file system, and Unix permission-related functions are restricted, too. Emscripten does not permit blocking I/O. Other blocking operations like sleep() block the browser event loop.

The properties and behavior of Python on WebAssembly platforms depend on the Emscripten-SDK or WASI-SDK version, WASM runtimes (browser, NodeJS, wasmtime), and Python build time flags. WebAssembly, Emscripten, and WASI are evolving standards; some features like networking may be supported in the future.

For Python in the browser, users should consider Pyodide or PyScript. PyScript is built on top of Pyodide, which itself is built on top of CPython and Emscripten. Pyodide provides access to browsers’ JavaScript and DOM APIs as well as limited networking capabilities with JavaScript’s XMLHttpRequest and Fetch APIs.

Process-related APIs are not available or always fail with an error. That includes APIs that spawn new processes ( fork() , execve() ), wait for processes ( waitpid() ), send signals ( kill() ), or otherwise interact with processes. The subprocess is importable but does not work.

The socket module is available, but is limited and behaves differently from other platforms. On Emscripten, sockets are always non-blocking and require additional JavaScript code and helpers on the server to proxy TCP through WebSockets; see Emscripten Networking for more information. WASI snapshot preview 1 only permits sockets from an existing file descriptor.

Some functions are stubs that either don’t do anything and always return hardcoded values.

Functions related to file descriptors, file permissions, file ownership, and links are limited and don’t support some operations. For example, WASI does not permit symlinks with absolute file names.

# Что такое библиотеки?

Библиотека или модуль — это набор готовых функций, объединенных общей темой. Например, в библиотеке math собраны функции для подсчёта математических величин.

Чтобы получить доступ к этим функциям, нужно командой import (англ. «импорт») в начале программы импортировать библиотеку. Это ещё называется «подключить модуль». В случае math пишут import math . Вот вызов извлекающей квадратный корень функции sqrt() из этой библиотеки:

Уже знакомая вам функция randint() из модуля random выбирает случайное целое число в заданном диапазоне. Но есть и другие, например:

  • random.choice(список) вернёт случайный элемент из списка
  • random.random() вернёт случайное дробное число от 0.0 до 1.0 (не включительно)

Если вам не нужны все функции библиотеки, можно подключить только нужные конструкцией from random import choice (из библиотеки random подключить функцию choice ).

Вот код для выбора подарка ребёнку. После явного подключения функции choice её можно использовать напрямую, без упоминания имени библиотеки.

Запустите этот код: результат может быть совсем другим!

Подключая библиотеку, можно присвоить ей новое имя. Например, если не хочется при каждом вызове писать полное имя:

Libraries

Most of the power of a programming language is in its libraries.

  • A library is a collection of files (called modules) that contains functions for use by other programs.
    • May also contain data values (e.g., numerical constants) and other things.
    • Library’s contents are supposed to be related, but there’s no way to enforce that.

    Libraries and modules

    A library is a collection of modules, but the terms are often used interchangeably, especially since many libraries only consist of a single module, so don’t worry if you mix them.

    A program must import a library module before using it.

    • Use import to load a library module into a program’s memory.
    • Then refer to things from the module as module_name.thing_name .
      • Python uses . to mean “part of”.
      • Have to refer to each item with the module’s name.
        • math.cos(pi) won’t work: the reference to pi doesn’t somehow “inherit” the function’s reference to math .

        Use help to learn about the contents of a library module.

        • Works just like help for a function.

        Import specific items from a library module to shorten programs.

        • Use from . import . to load only specific items from a library module.
        • Then refer to them directly without library name as prefix.

        Create an alias for a library module when importing it to shorten programs.

        • Use import . as . to give a library a short alias while importing it.
        • Then refer to items in the library using that shortened name.
        • Commonly used for libraries that are frequently used or have long names.
          • E.g., the matplotlib plotting library is often aliased as mpl .

          Exploring the Math Module

          1. What function from the math module can you use to calculate a square root without using sqrt ?
          2. Since the library contains this function, why does sqrt exist?

          Solution

          1. Using help(math) we see that we’ve got pow(x,y) in addition to sqrt(x) , so we could use pow(x, 0.5) to find a square root.
          2. The sqrt(x) function is arguably more readable than pow(x, 0.5) when implementing equations. Readability is a cornerstone of good programming, so it makes sense to provide a special function for this specific common case.

            Also, the design of Python’s math library has its origin in the C standard, which includes both sqrt(x) and pow(x,y) , so a little bit of the history of programming is showing in Python’s function names.

          Locating the Right Module

          You want to select a random character from a string:

          1. Which standard library module could help you?
          2. Which function would you select from that module? Are there alternatives?
          3. Try to write a program that uses the function.

          Solution

          The random module seems like it could help.

          The string has 11 characters, each having a positional index from 0 to 10. You could use the random.randrange or random.randint functions to get a random integer between 0 and 10, and then select the bases character at that index:

          or more compactly:

          Perhaps you found the random.sample function? It allows for slightly less typing but might be a bit harder to understand just by reading:

          Note that this function returns a list of values. We will learn about lists in episode 11.

          The simplest and shortest solution is the random.choice function that does exactly what we want:

          Jigsaw Puzzle (Parson’s Problem) Programming Example

          Rearrange the following statements so that a random DNA base is printed and its index in the string. Not all statements may be needed. Feel free to use/add intermediate variables.

          Solution

          When Is Help Available?

          When a colleague of yours types help(math) , Python reports an error:

          What has your colleague forgotten to do?

          Solution

          Importing the math module ( import math )

          Importing With Aliases

          1. Fill in the blanks so that the program below prints 90.0 .
          2. Rewrite the program so that it uses import without as .
          3. Which form do you find easier to read?

          Solution

          can be written as

          Since you just wrote the code and are familiar with it, you might actually find the first version easier to read. But when trying to read a huge piece of code written by someone else, or when getting back to your own huge piece of code after several months, non-abbreviated names are often easier, except where there are clear abbreviation conventions.

          There Are Many Ways To Import Libraries!

          1. print(«sin(pi/2) language-plaintext highlighter-rouge»>print(«sin(pi/2) language-plaintext highlighter-rouge»>print(«sin(pi/2) language-plaintext highlighter-rouge»>from math import sin, pi
          2. import math
          3. import math as m
          4. from math import *

          Solution

          1. Library calls 1 and 4. In order to directly refer to sin and pi without the library name as prefix, you need to use the from . import . statement. Whereas library call 1 specifically imports the two functions sin and pi , library call 4 imports all functions in the math module.
          2. Library call 3. Here sin and pi are referred to with a shortened library name m instead of math . Library call 3 does exactly that using the import . as . syntax — it creates an alias for math in the form of the shortened name m .
          3. Library call 2. Here sin and pi are referred to with the regular library name math , so the regular import . call suffices.

          Importing Specific Items

          1. Fill in the blanks so that the program below prints 90.0 .
          2. Do you find this version easier to read than preceding ones?
          3. Why wouldn’t programmers always use this form of import ?

          Solution

          Most likely you find this version easier to read since it’s less dense. The main reason not to use this form of import is to avoid name clashes. For instance, you wouldn’t import degrees this way if you also wanted to use the name degrees for a variable or function of your own. Or if you were to also import a function named degrees from another library.

          6 основных библиотек для программирования на Python

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

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

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

          • Keras

          Тип – нейросетевая библиотека.

          Начальная версия – март 2015.

          Keras – открытая нейросетевая библиотека, написанная на языке Python. Нацелена на оперативную работу с сетями глубокого обучения, при этом спроектирована так, чтобы быть компактной, модульной и расширяемой.

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

          В связи с тем, что Keras создает вычислительный граф с помощью серверной инфраструктуры, а затем использует его для выполнения операций, он работает медленнее, чем другие библиотеки машинного обучения. Тем не менее, все модели в Keras являются портативными.

          • Легко отлаживать и исследовать, так как она полностью написана на Python.
          • Содержит многочисленные реализации широко применяемых строительных блоков нейронных сетей, таких как функции активации, уровни, цели и оптимизаторы.
          • Невероятная выразительность и гибкость делают его идеальным для инновационных исследований.
          • Предлагает несколько предварительно обработанных наборов данных и предварительно обученных моделей, таких как Inception, MNIST, ResNet, SqueezeNet и VGG.
          • Обеспечивает поддержку почти всех моделей нейронных сетей, включая свёрточную, встраиваемую, полностью подключенную, объединяющую в пул и рекуррентную. Более того, эти модели можно комбинировать для разработки еще более сложных моделей.
          • Работает как на CPU (центральном процессоре), так и на GPU (ядре процессора)
          • Уже используется Netflix, Square, Uber и Yelp.
          • Для исследования глубокого обучения. Принят исследователями в ЦЕРН и НАСА.
          • Популярный среди стартапов, разрабатывающих продукты, основанные на глубоком обучении.
          • NumPy

          Тип – техническая вычислительная библиотека.

          Начальная версия – 1995 (как Numeric).

          NumPy был создан Трэвисом Олифантом в 2005 году путем включения функций конкурирующей библиотеки Numarray в библиотеку Numeric и применения обширных модификаций. В бесплатной библиотеке с открытым исходным кодом есть несколько соавторов со всего мира.

          Одна из самых популярных библиотек машинного обучения в Python, TensorFlow и несколько других библиотек используют библиотеку NumPy Python внутри себя для выполнения нескольких операций над тензорами.

          • Активная поддержка сообщества
          • Полностью бесплатный и открытый исходный код
          • Сложные матричные операции, такие как матричное умножение
          • Интерактивный и супер простой в использовании
          • Облегчает сложные математические реализации
          • Легко кодировать с удобочитаемыми концепциями
          • Для выполнения сложных математических вычислений
          • Для представления изображений, звуковых волн и других форм двоичных необработанных потоков в виде массива действительных чисел в N-мерном
          • Для проектов машинного обучения
          • Pillow

          Тип – Библиотека обработки изображений

          Начальная версия – 1995 (Как Python Imaging Library или PIL)

          2011 (Как Pillow)

          Pillow — это библиотека Python, которая почти так же стара, как и язык программирования, для которого она была разработана. На самом деле, Pillow — это форк для PIL (Python Imaging Library). Свободно используемая библиотека Python необходима для открытия, манипулирования и сохранения разнообразных файлов изображений.

          Pillow была принята в качестве замены оригинального PIL в нескольких дистрибутивах Linux, в частности, Debian и Ubuntu. Тем не менее, он также доступен для MacOS и Windows.

          • Добавляет текст к изображениям
          • Улучшение и фильтрация изображения, включая размытие, регулировку яркости, контур и резкость
          • Маскировка и прозрачность
          • Пиксельные манипуляции
          • Обеспечивает поддержку множества форматов файлов изображений, включая BMP, GIF, JPEG, PNG, PPM и TIFF. Обеспечивает поддержку для создания новых декодеров файлов с целью расширения библиотеки доступных форматов файлов.
          • Для обработки изображений
          • PYGLET

          Тип — Библиотека разработки игр

          Начальная версия – апрель 2015

          Библиотека многоплатформенного кадрирования и мультимедии для Python, PYGLET — это популярное имя для разработки игр с использованием Python. В дополнение к играм, библиотека разработана для создания визуально насыщенных приложений.

          В дополнение к поддержке кадрирования, PYGLET обеспечивает поддержку загрузки изображений и видео, воспроизведения звуков и музыки, графики OpenGL и обработки событий пользовательского интерфейса.

          • Использование нескольких окон и рабочих столов с несколькими мониторами
          • Загрузка изображений, звука и видео практически во всех форматах
          • Нет внешних зависимостей и требований к установке
          • Предоставляется в соответствии с лицензией BSD с открытым исходным кодом, поэтому может свободно использоваться как в личных, так и в коммерческих целях
          • Обеспечивает поддержку как Python 2, так и Python 3
          • Для разработки визуально насыщенных приложений
          • Для разработки игр
          • Requests

          Тип – Библиотека HTTP

          Начальная версия – февраль 2011

          Requests — HTTP библиотека Python, направлена на то, чтобы сделать запросы HTTP проще и удобнее. Разработанный Кеннетом Рейтцем и несколькими другими участниками, Requests позволяет отправлять запросы HTTP/1.1 без вмешательства человека.

          От Nike и Spotify до Amazon и Microsoft десятки крупных организаций используют запросы внутренне, чтобы лучше справляться с HTTP. Написанная полностью на Python, Requests доступна в виде бесплатной библиотеки с открытым исходным кодом под лицензией Apache2.

          • Автоматическое декодирование контента
          • Базовая/дайджест-аутентификация
          • Проверка SSL в браузерном стиле
          • Частичные запросы и время ожидания соединения
          • Обеспечивает поддержку прокси-серверов .netrc и HTTP (S)
          • Сеансы с сохранением cookie
          • Ответное тело Unicode
          • Позволяет отправлять запросы HTTP/1.1 с использованием Python и добавлять контенты, такие как заголовки, данные форм и многокомпонентные файлы
          • Для автоматического добавления строк запроса в URL
          • Для автоматического кодирования данных POST
          • TensorFlow

          Тип – Библиотека машинного обучения

          Начальная версия – ноябрь 2015

          TensorFlow — это бесплатная библиотека Python с открытым исходным кодом, предназначенная для решения ряда задач, связанных с потоком данных и дифференцируемым программированием. Тем не менее, символическая математическая библиотека TensorFlow является одной из наиболее широко используемых библиотек машинного обучения Python.

          Разработанный Google Brain для внутреннего использования, библиотека используется для коммерческих и исследовательских целей.

          Тензорными являются N-мерные матрицы, которые представляют данные. Библиотека TensorFlow позволяет писать новые алгоритмы, включающие большое количество тензорных операций.

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

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *